<template>
  <div class="overlay-page">
    <div class="visual-layout">
      <div class="grid-item grid-one visual-layout-head flex align-center position-relative">
        <img class="title-img" src="../../../assets/title-img.png" alt="智慧能源信息平台">
        <visual-menu-button class="visual-menu-button"></visual-menu-button>
        <el-tooltip content="返回首页" effect="light">
          <el-button
            icon="el-icon-s-home" type="primary" circle
            style="margin-left: auto;z-index: 999;"
            @click="$router.push('/')"
          ></el-button>
        </el-tooltip>
      </div>
      <div class="grid-item grid-two">
        <div class="grids-4">
          <div class="grids-4-item border-radius flex-center direction-column">
            <span class="margin-bottom text font-6">节能项目总数</span>
            <span class="value font-8">{{formatNumber(info.projectNumber)}}<i class="unit">个</i></span>
          </div>
          <div class="grids-4-item border-radius flex-center direction-column">
            <span class="margin-bottom text font-6">节能项目总投资</span>
            <span class="value font-8">{{formatNumber(info.projectTotalInvestment)}}<i class="unit">万元</i></span>
          </div>
          <div class="grids-4-item border-radius flex-center direction-column">
            <span class="margin-bottom text font-6">财政补助总金额</span>
            <span class="value font-8">{{formatNumber(info.financialSubsidy)}}<i class="unit">万元</i></span>
          </div>
          <div class="grids-4-item border-radius flex-center direction-column">
            <span class="margin-bottom text font-6">政府补助率</span>
            <span class="value font-8">{{formatNumber(info.subsidyRate)}}<i class="unit">%</i></span>
          </div>
        </div>
      </div>
      <div class="grid-item grid-three">
        <map-center type="1"></map-center>
      </div>
      <div class="grid-item grid-four">
        <div class="grids-5">
          <div class="grids-5-item border-radius flex-center direction-column">
            <span class="margin-bottom text font-6">10000吨标准煤企业数</span>
            <span class="value font-8">{{formatNumber(info.tenThousand)}}<i class="unit">家</i></span>
          </div>
          <div class="grids-5-item border-radius flex-center direction-column">
            <span class="margin-bottom text font-6">5000吨标准煤企业数</span>
            <span class="value font-8">{{formatNumber(info.fiveThousand)}}<i class="unit">家</i></span>
          </div>
          <div class="grids-5-item border-radius flex-center direction-column">
            <span class="margin-bottom text font-6">能源管理员数</span>
            <span class="value font-8">{{formatNumber(info.administratorsNumber)}}<i class="unit">人</i></span>
          </div>
          <div class="grids-5-item border-radius flex-center direction-column">
            <span class="margin-bottom text font-6">能源管理员平均数</span>
            <span class="value font-8">{{formatNumber(info.administratorsAverageNumber)}}<i class="unit">人</i></span>
          </div>
          <div class="grids-5-item border-radius flex-center direction-column grids-5-item-last">
            <span class="margin-bottom text font-6">能耗管理平台接入率</span>
            <span class="value font-8">{{info.platformAccessRate}}<i class="unit">%</i></span>
          </div>
        </div>
      </div>
      <div class="grid-item grid-five overflow-hidden">
        <div class="grid-item-five">
          <div class="text">绿色工厂</div>
        </div>
        <div class="grid-item-five">
          <el-carousel height="100%" :interval="3000" indicator-position="none">
            <el-carousel-item v-for="item in pictures1" :key="item.id">
              <img class="factory-image" :src="item.url" :alt="item.url" @click="navigateToEnterprisePicture">
            </el-carousel-item>
          </el-carousel>
        </div>
        <div class="grid-item-five">
          <div class="text">绿色园区</div>
        </div>
        <div class="grid-item-five">
          <el-carousel height="100%" :interval="3000" indicator-position="none">
            <el-carousel-item v-for="item in pictures2" :key="item.id">
              <img class="factory-image" :src="item.url" :alt="item.url" @click="navigateToEnterprisePicture">
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
      <div class="grid-item grid-six">
        <div class="width-100 height-100">
          <div class="factories width-100 height-100 overflow-hidden">
            <div class="factories-wrap" ref="wrap">
              <div class="factory" v-for="(item, index) in enterpriseLists" :key="index">
                <router-link
                  :to="{name: 'EnterpriseAnalysis', query: {
                  enterpriseCode: item.id,
                }}"
                  class="link"
                >
                  <dl>
                    <dt>{{item.name}}</dt>
                    <dd>用水量：{{item.water}} {{getUnitName('water')}}</dd>
                    <dd>用电量：{{item.electric}} {{getUnitName('electric')}}</dd>
                    <dd>用气量：{{item.gas}} {{getUnitName('gas')}}</dd>
                    <dd>综合能耗：{{item.consumption}} {{getUnitName('other')}}</dd>
                  </dl>
                </router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="grid-item grid-eight" ref="container">
        <v-chart ref="chart2" :option="barOption"></v-chart>
      </div>
    </div>
  </div>
</template>

<script>
import { loadEnterpriseOverview, loadEnterpriseEnergyConsumptionLevel } from '@/api/enterprose'
import { getListByType } from '@/api/pictureResources'
import { loadEnergySavingProject } from '@/api/energySavingProject'
import VisualXxx from '@/mixins/visual-xxx'
import MapCenterClick from '@/mixins/map-center-click'
import elementResizeDetectorMaker from 'element-resize-detector'
import { defaultNumber } from '@/utils'

const erd = elementResizeDetectorMaker()
export default {
  name: 'visual-enterprise-energy',
  mixins: [VisualXxx, MapCenterClick],
  data () {
    return {
      info: {
        // 10000吨标准煤企业数量
        tenThousand: '',
        // 5000吨标准煤企业数量
        fiveThousand: '',
        // 5000吨以下标准煤企业数量
        thousand: '',
        // 管理员数量
        administratorsNumber: '',
        // 管理员平均数量
        administratorsAverageNumber: '',
        // 能耗管理平台接入率
        platformAccessRate: '',
        // 未接入企业数量百分比
        numberOfUnconnectedPercentage: '',

        // 节能项目总数
        projectNumber: '',
        // 节能项目总投资
        projectTotalInvestment: '',
        // 财政补助总金额
        financialSubsidy: '',
        // 政府补助率
        subsidyRate: '',
      },

      pictures1: [],
      pictures2: [],

      barMap: {},
    }
  },
  computed: {
    barOption () {
      const barMap = this.barMap
      const levels = Object.keys(barMap)
      const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
      return {
        title: {
          text: '年能耗等级企业数',
          top: '2%',
          textStyle: {
            color: '#4b84e0',
            fontWeight: 'normal',
            fontSize: '1.4rem'
          }
        },
        tooltip: {
          show: true,
          position: 'top',
          valueFormatter: value => `${defaultNumber(value)}家`
        },
        legend: {
          show: false,
        },
        grid: {
          top: '70px',
          bottom: '30px',
        },
        xAxis: {
          show: false,
          type: 'value',
          splitLine: {
            show: false,
          },
          name: '个'
        },
        yAxis: {
          type: 'category',
          data: [...levels],
          axisLabel: {
            show: false,
          },
        },
        series: [
          {
            type: 'bar',
            name: '用能企业数',
            label: {
              show: true,
              position: 'insideLeft',
              align: 'left',
              textBorderWidth: 0,
              color: '#4b84e0',
              distance: 10,
              rotate: 0,
              fontSize: 16,
              formatter: '{b}：{c}家',
              rich: {
                name: {}
              }
            },
            data: [
              ...levels.map((key, i) => ({
                value: Number(barMap[key]),
                itemStyle: {
                  color: colors[i % colors.length],
                },
              }))
            ],
          }
        ],
      }
    },
  },
  mounted () {
    this.loadEnterpriseOverview()
    this.loadEnergySavingProject()
    this.loadEnterpriseEnergyConsumptionLevel()
    this.query1()
    this.query2()
    try {
      this.showTip()
    } catch (e) {}

    const vm = this
    erd.listenTo(this.$refs.container, function () {
      vm.$refs.chart2.resize({
        animation: {
          duration: 1000,
        }
      })
    })
  },
  beforeDestroy () {
    this.timer1 && clearInterval(this.timer1)
    this.timer2 && clearInterval(this.timer2)

    erd.removeAllListeners(this.$refs.container)
  },
  methods: {
    bindEventOnChart () {
      const chart1 = this.$refs.chart1.chart
      const chart2 = this.$refs.chart2.chart
      chart1.on('click', this.clickHandler)
      chart2.on('click', this.clickHandler)
    },
    unbindEventOnChart () {
      const chart1 = this.$refs.chart1.chart
      const chart2 = this.$refs.chart2.chart
      chart1.off('click', this.clickHandler)
      chart2.off('click', this.clickHandler)
    },
    clickHandler (e) {
      const dataIndex = e.dataIndex
      const seriesType = e.seriesType
      let energyConsumptionLevel = ''
      if (seriesType === 'bar') {
        // eslint-disable-next-line
        energyConsumptionLevel = dataIndex == 1 ? '1' : '2'
      } else if (seriesType === 'pie') {
        // eslint-disable-next-line
        energyConsumptionLevel = dataIndex == 3 ? '' : String(dataIndex + 1)
      }
      this.$router.push({
        name: 'EnterpriseManagement2',
        query: {
          energyConsumptionLevel
        }
      }).catch(() => {})
    },
    navigateToEnterprisePicture () {
      this.$router.push({
        name: 'EnterprisePicture'
      }).catch(() => {})
    },
    showTip () {
      const m = 2
      let i = 0
      const chart1 = this.$refs.chart1
      this.timer1 = setInterval(() => {
        i++
        if (i >= m) {
          i = 0
        }
        if (chart1) {
          chart1.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: i,
          })
        } else {
          clearInterval(this.timer1)
        }
      }, 3000)

      const n = 4
      let j = 0
      const chart2 = this.$refs.chart2
      this.timer2 = setInterval(() => {
        j++
        if (j >= n) {
          j = 0
        }
        if (chart2) {
          chart2.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: j,
          })
        } else {
          clearInterval(this.timer2)
        }
      }, 3000)
    },
    loadEnterpriseOverview () {
      return loadEnterpriseOverview().then(res => {
        if (res.code === 200) {
          this.info = {
            ...this.info,
            ...res.data
          }
        }
      })
    },
    formatNumber (number) {
      return Number(number).toLocaleString()
    },
    queryPicture (type = '') {
      return getListByType({ type })
    },
    query1 () {
      this.queryPicture('1').then(res => {
        if (res.code === 200) {
          this.pictures1 = res.data
        }
      })
    },
    query2 () {
      this.queryPicture('2').then(res => {
        if (res.code === 200) {
          this.pictures2 = res.data
        }
      })
    },
    loadEnergySavingProject () {
      return loadEnergySavingProject().then(res => {
        if (res.code === 200) {
          this.info = {
            ...this.info,
            ...res.data
          }
        }
      })
    },
    getUnitName (type) {
      const energyUnits = this.$store.state.energyUnits
      const target = energyUnits.find(v => v.key === type)
      return target ? target.value : '吨标准煤'
    },
    loadEnterpriseEnergyConsumptionLevel () {
      return loadEnterpriseEnergyConsumptionLevel().then(res => {
        res.data = res.data || {}
        if (res.code === 200) {
          this.barMap = res.data
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import "@/assets/style/variable.scss";
$color-1: #0c4092;
$color-2: #4b84e0;
$color-3: #aac4ee;
$item-background: rgba(0,0,0,0.25);

.visual-layout {
  grid-template-rows: 6.5vh 2fr 1fr 30vh;
  grid-template-columns: repeat(7, 1fr);
}
.grid-one {
  grid-column-start: 1;
  grid-column-end: 8;
}
.grid-five,
.grid-two {
  grid-column-start: 1;
  grid-column-end: 3;
}
.grid-six,
.grid-three {
  grid-column-start: 3;
  grid-column-end: 6;
}
.grid-eight,
.grid-four {
  grid-column-start: 6;
  grid-column-end: 8;
}
.grid-three {
  grid-row-start: 2;
  grid-row-end: 4;
}
.grid-six {
  grid-row-start: 4;
  grid-row-end: 5;
  grid-column-start: 3;
  grid-column-end: 6;
}
.grid-eight,
.grid-five {
  grid-row-start: 3;
  grid-row-end: 5;
}
.grid-six,
.grid-four,
.grid-two {
  background: transparent;
  padding: 0;
}
.grids-4 {
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-gap: $gutter;
}
.grids-5-item,
.grids-4-item {
  background: $item-background;
}
.grids-5 {
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-gap: $gutter;
}
.grids-5-item-last {
  grid-column-start: 1;
  grid-column-end: 3;
}
.grid-four,
.grid-two {
  .unit {
    font-size: 1rem;
    font-style: normal;
    color: $color-2;
    margin-left: .5rem;
  }
}
.factory-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
  & + .factory-image {
    margin-top: $gutter / 2;
  }
}
.grid-five {
  ::v-deep .el-carousel {
    width: 100%;
    height: 100%;
  }
}
.grid-five {
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-rows: 50px 1fr 50px 1fr;
  padding: 0;
  background: transparent;
}
.grid-item-five {
  background: $item-background;
  padding-left: $gutter;
  padding-right: $gutter;
  .text {
    padding-left: 0;
    padding-right: 0;
    line-height: 50px;
    font-size: 1rem;
  }
  ::v-deep .el-carousel__arrow {
    background: $color-2;
  }
}
</style>
